package java_language;

/**
 * 浅拷贝的示例代码，内部对象共用
 *
 * @Author Jun jie Yi
 * 2022/3/22 10:47
 */
public class ShallowAndDeepCopy {
    public static void main(String[] args) {

        Person person1 = new Person(new Address("武汉"));
        Person person1Copy = person1.clone();
        System.out.println(person1.getAddress() == person1Copy.getAddress());

    }
}

class Address implements Cloneable {
    private String name;

    public Address(String name) {
        this.name = name;
    }

    @Override
    public Address clone() {
        try {
            return (Address) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

class Person implements Cloneable {

    private Address address;

    public Person(Address address) {
        this.address = address;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    // 省略构造函数、Getter&Setter方法
    @Override
    public Person clone() {
        try {
            Person person = (Person) super.clone();
            return person;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}
